package com.budayi.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author LIBOFEI
 * @ClassName ReponseUtil
 * @description
 * @date 2021/4/30 23:30
 * @Version 1.0
 **/
public class ReponseUtil {

    /*** *
     * 全局返回json格式错误信息工具方法
     * @param exchange 上下文对象
     * @param code 错误码
     * @param errorMessage 错误信息
     * @author LIBOFEI
     * @date 23:32 2021/4/30
     * @return java.lang.Object
     * @Version  1.0
    **/
    public static Object reponse(ServerWebExchange exchange,int code,String errorMessage){
        return Mono.defer(() -> {
            byte[] bytes = new byte[0];
            try {
                bytes = new ObjectMapper().writeValueAsBytes(JsonResult.failure(code,errorMessage));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8.toString());
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        });
    }
}
